# -*- coding:utf-8 -*-

from flask import request, render_template, jsonify
from app.models.statistic import Daily_Statistic as DS, Stats_Cache as SC
from app.tools.permission import permission
from flask_login import login_required
from app import db
import datetime
from . import home


@home.before_request
@login_required
def check_permission():	#检查权限
	return

def stats(user_type, date, stats_type):	#计算统计数据
	data = {}
	pc_count, mobile_count, total, dates = [], [], [], []	#pc端数量，移动端数量，总数量，对应的日期
	attr = {'stats_type': stats_type}
	if user_type != '0':	#不区分商家与个人
		attr['user_type'] = user_type
	if date != '365':	#统计的时间段非最近一年，按天进行统计
		today = datetime.date.today()
		delta = datetime.timedelta(days=0-int(date))
		start = today + delta
		pc = DS.query.filter_by(**attr).filter(DS.source==0, DS.date.between(start, today)).all()
		mobile = DS.query.filter_by(**attr).filter(DS.source==1, DS.date.between(start, today)).all()
		for item in pc:
			pc_count.append(item.count)
			dates.append(datetime.datetime.strftime(item.date, "%Y/%m/%d"))
		for item in mobile:
			mobile_count.append(item.count)
	else:	#最近一年，按月进行统计
		today = datetime.date.today()
		year = today.year
		month = today.month
		for i in range(1, 13):
			month -= 1
			if month == 0:
				month = 12
				year -= 1
			ym = str(year) + str(month)
			pc = DS.query.filter_by(**attr).filter(DS.source==0, DS.month==ym).all()
			mobile = DS.query.filter_by(**attr).filter(DS.source==1, DS.month==ym).all()
			add = 0
			for item in pc:
				add += item.count
			pc_count.append(add)
			add = 0
			for item in mobile:
				add += item.count
			mobile_count.append(add)
			dates.append(str(year)+'/'+str(month))
		pc_count.reverse()
		mobile_count.reverse()
		dates.reverse()	#倒序
	for item in zip(pc_count, mobile_count):	#计算总量
		num = 0
		for i in item:
			num += i
		total.append(num)
	data['dates'] = dates
	data['pc_count'] = pc_count
	data['mobile_count'] = mobile_count
	data['total'] = total
	pc_count, mobile_count, dates, total = '', '' ,'' ,''
	for item in data['dates']:
		dates = dates + str(item) + ','
	for item in data['pc_count']:
		pc_count = pc_count + str(item) + ','
	for item in data['mobile_count']:
		mobile_count = mobile_count + str(item) + ','
	for item in data['total']:
		total = total + str(item) + ','
	today = datetime.date.today()
	sc = SC(user_type=user_type, stats_type=stats_type, date=date, pc_count=pc_count, 
		mobile_count=mobile_count, total=total, dates=dates, cache_date=today)	#存储计算结果，避免重复计算，每天只需要计算一次
	db.session.add(sc)
	db.session.commit()
	return data

@home.route('/')
def index():
	return render_template('home/home.html')

@home.route('/get_stats/')
def get_stats():	#获取统计数据
	values = request.values
	user_type = values.get('user_type')
	stats_type = values.get('stats_type')	#统计对象
	date = values.get('date')
	if user_type is None or stats_type is None or date is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	today = datetime.date.today()
	sc = SC.query.filter_by(user_type=user_type, stats_type=stats_type, date=date, cache_date=today).first()	#查询是否已经有计算结果
	if sc:
		data = {}
		data['pc_count'] = sc.pc_count.split(',')[:-1]
		data['mobile_count'] = sc.mobile_count.split(',')[:-1]
		data['total'] = sc.total.split(',')[:-1]
		data['dates'] = sc.dates.split(',')[:-1]
	else:	#第一次计算
		data = stats(user_type, date, stats_type)
	return jsonify({'state': 0, 'data': data})
